import json
from django.http import JsonResponse
from django.shortcuts import render
from user.models import UserProfile
import hashlib
from django.conf import settings
import time
import jwt

# Create your views here.

# 异常码（10200---10299）

def tokens(request):
    # 用户登录校验和回话的存储    对应login的HTML    API：http://127.0.0.1:8000/v1/tokens
    if request.method != 'POST':
        # 判断是否是post请求
        result = {'code': 10200, 'error': 'The request method not post'}
        return JsonResponse(result)

    # 从前端取数据
    json_str = request.body
    json_obj = json.loads(json_str)
    username = json_obj['username']
    password = json_obj['password']

    # 从数据库取出数据并进行校验数据
    try:
        user = UserProfile.objects.get(username=username)
        # print(user)
    except Exception as e:
        result = {'code': 10202, 'error': 'The username or password is wrong'}
        return JsonResponse(result)
    p_m = hashlib.md5()
    p_m.update(password.encode())
    if p_m.hexdigest() != user.password:
        # print(user.password)
        result = {'code': 10203, 'error': 'The username or password is wrong'}
        return JsonResponse(result)

    # 记录回话状态
    token = make_token(username)
    result = {'code': 200, 'username': username, 'data': {'token': token}}    # 'token': token
    return JsonResponse(result)

# 利用JWT技术做cook的存储
def make_token(username, expire=3600*24):

    key = settings.JWT_TOKEN_KEY
    now_t = time.time()
    payload_data = {'username': username, 'exp': now_t+expire}
    return jwt.encode(payload_data, key, algorithm='HS256')